package com.yzk.train.member.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yzk.train.common.request.MemberTicketReq;
import com.yzk.train.common.response.PageResp;
import com.yzk.train.common.utils.SnowUtil;
import com.yzk.train.member.entity.Ticket;
import com.yzk.train.member.entity.TicketExample;
import com.yzk.train.member.mapper.TicketMapper;
import com.yzk.train.member.request.TicketQueryReq;
import com.yzk.train.member.response.TicketQueryResp;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TicketService {

    @Resource
    private TicketMapper ticketMapper;

    /**
     * 会员购买车票，插入车票记录
     *
     * @param req
     */
    public void save(MemberTicketReq req) {
        DateTime now = DateTime.now();
        Ticket ticket = BeanUtil.copyProperties(req, Ticket.class);
        ticket.setId(SnowUtil.getSnowflakeNextId());
        ticket.setCreateTime(now);
        ticket.setUpdateTime(now);
        ticketMapper.insert(ticket);
    }

    /**
     * 查询车票列表
     *
     * @param req
     */
    public PageResp<TicketQueryResp> queryList(TicketQueryReq req) {
        TicketExample ticketExample = new TicketExample();
        ticketExample.setOrderByClause("id desc");
        if (ObjUtil.isNotNull(req.getMemberId())) {
            ticketExample.createCriteria().andMemberIdEqualTo(req.getMemberId());
        }
        // 使用分页插件
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<Ticket> tickets = ticketMapper.selectByExample(ticketExample);
        // 使用 PageInfo 包装查询结果
        PageInfo<Ticket> pageInfo = new PageInfo<>(tickets);
        // 转换为 PageResp
        List<TicketQueryResp> list = BeanUtil.copyToList(tickets, TicketQueryResp.class);
        return new PageResp<>(pageInfo.getTotal(), list);
    }

    /**
     * 根据ID删除车票
     *
     * @param id
     */
    public void delete(Long id) {
        ticketMapper.deleteByPrimaryKey(id);
    }

}
